/*
 * Author Ahmed Abdelhalim - 2009
 * Email: englemo@hotmail.com
 * Please do not remove the above lines
 */
package remoteserver;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * This is the entry class of the server
 */
public class ServerInitiator extends Thread{
    private JFrame frame;
    private JPanel cPanel = new JPanel();
    public boolean IsWorking;
    public ImageIcon imageIcon = null;
    public ServerInitiator(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setVisible(true);
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        start();
    }
    
    public void drawGUI(){
        frame.setLayout(new BorderLayout());
        frame.getContentPane().add(cPanel,BorderLayout.CENTER);
        cPanel.setFocusable(true);
        frame.setVisible(true);
        Toolkit tk = Toolkit.getDefaultToolkit();  
        int xSize = ((int) tk.getScreenSize().getWidth());  
        int ySize = ((int) tk.getScreenSize().getHeight());  
        frame.setPreferredSize(new Dimension(xSize/2, ySize/2));        
        frame.setMinimumSize(new Dimension(xSize/3, ySize/3));
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {       
                IsWorking = false;
            }
        });
    }
    
    @Override
    public void run(){
        drawGUI();
        IsWorking = true;
      
        //Read screenshots of the client then draw them
        while(IsWorking){
                //Recieve client screenshot and resize it to the current panel size
                if (imageIcon != null){
                   System.out.println("New image recieved");
                   Image image = imageIcon.getImage();
                   image = image.getScaledInstance(cPanel.getWidth(),cPanel.getHeight()
                                                       ,Image.SCALE_FAST);
                   //Draw the recieved screenshot
                   Graphics graphics = cPanel.getGraphics();
                   graphics.drawImage(image, 0, 0, cPanel.getWidth(),cPanel.getHeight(),cPanel);                       
                }
            }
        }
    }
